'''
Description: 
Author: Zilu
Date: 2021-11-15 11:26:15
Version: 
LastEditTime: 2021-11-15 17:09:24
LastEditors: Zilu
'''

# TCP 创建的是可靠的连接
from os import times
import socket

# AF_INET 指定用 IPv4 协议，SOCK_STREAM 指定面向流的TCP协议
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 建立连接
# 参数是一个tuple，包含地址和端口号。
s.connect(('www.sina.com', 80))

# 新浪提供网页服务的服务器必须把端口号固定在80端口 
# 端口号小于1024的是Internet标准服务的端口，端口号大于1024的，可以任意使用。

# 使用get请求
s.send(b'GET /HTTP/1.1\r\nHost: www.sina.com.cn\r\nConnection: close\r\n\r\n')
buffer = []
while True:
    d = s.recv(1024)
    if d:
        buffer.append(d.decode('utf-8'))
    else:
        break

data = ''.join(buffer)
data
s.close()

header, html = data.split('\r\n\r\n', 1)
print(header)
with open('网络编程/sina.html','w') as f:
    f.write(html)

import socket
import threading
import time

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 9999))

# listen 监听端口
s.listen(5)     # 最多 5 个连接
print('Waiting for connection...')

def tcplink(sock:socket.socket, addr):
    print('Accept new connection from %s:%s' % (sock, addr))
    sock.send(b'Welcome!')
    while True:
        data = sock.recv(1024)
        time.sleep(1)
        if not data or data.decode('utf-8') == 'exit':
            break
        sock.send(('Hello, %s!' % data.decode('utf-8')).encode('utf-8'))
    sock.close()
    print('Connection from %s:%s closed.' % addr)

while True:
    sock, addr = s.accept()
    t = threading.Thread(target=tcplink, args=(sock, addr))
    t.start()






